const express = require('express');
const path = require('path');
const favicon = require('serve-favicon');
// const logger = require('morgan');
const winston = require("./src/server/utils/Logger").winston;
const cookieParser = require('cookie-parser');
const bodyParser = require('body-parser');

const initAccessToken = require('./src/server/service/WechatService').initAccessToken;
initAccessToken();

const home = require('./src/server/routes/home');
const activities = require('./src/server/routes/activities');
const business = require('./src/server/routes/business');
const user = require('./src/server/routes/user');
const wechat = require('./src/server/routes/wechat');



const app = express();
//运行环境
process.env.NODE_ENV = 'development'; // production

// 模板引擎
app.set('views', path.join(__dirname, 'src/client/views'));
app.set('view engine', 'hbs');

// uncomment after placing your favicon in /public
app.use(favicon(path.join(__dirname, '/src/client/static/img', 'favicon.ico')));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'src/client/static')));
// app.use(logger('dev'));
app.use(require('./src/server/utils/RequestLogger').create(winston));
//后端路由
app.use('/', home);
app.use('/activities', activities);
app.use('/business', business);
app.use('/user', user);
app.use('/wechat', wechat);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  let err = new Error('Not Found');
  err.status = 404;
  next(err);
});

// error handler
app.use(function(err, req, res) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;
